package com.bstek.uflo.designer.deserializer.impl;

import java.util.List;

import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.bstek.uflo.designer.model.Shape;
import com.bstek.uflo.designer.model.SubProcessType;
import com.bstek.uflo.designer.model.SubProcessVariable;
import com.bstek.uflo.designer.model.node.SubProcess;

/**
 * @author matt.yao@bstek.com
 * @since 1.0
 */
@Service
public class SubProcessDeserializer extends NodeDeserializer {

	public Shape execute(Element currentElement) throws Exception {
		SubProcess subProcess = new SubProcess();
		super.deserializeCommonAttribute(subProcess, currentElement);
		String subprocessId = currentElement.attributeValue("subprocess-id");
		String subprocessName = currentElement.attributeValue("subprocess-name");
		String subprocessKey = currentElement.attributeValue("subprocess-key");
		subProcess.setSubprocessId(subprocessId);
		subProcess.setSubprocessName(subprocessName);
		subProcess.setSubprocessKey(subprocessKey);
		if (StringUtils.hasText(subprocessId)) {
			subProcess.setSubprocessType(SubProcessType.Id.name());
		} else if (StringUtils.hasText(subprocessKey)) {
			subProcess.setSubprocessType(SubProcessType.Key.name());
		} else {
			subProcess.setSubprocessType(SubProcessType.Name.name());
		}
		List<?> outVariableElements = currentElement.elements("out-subprocess-variable");
		for (Object outVariableObj : outVariableElements) {
			Element outVariableElement = (Element) outVariableObj;
			SubProcessVariable subProcessVariable = new SubProcessVariable();
			subProcessVariable.setOutParameterKey(outVariableElement.attributeValue("out-parameter-key"));
			subProcessVariable.setInParameterKey(outVariableElement.attributeValue("in-parameter-key"));
			subProcess.getOutVariables().add(subProcessVariable);
		}
		return subProcess;
	}

	public boolean support(String name) {
		return name.equals("subprocess") ? true : false;
	}

}
